package com.training2.bookstore.product.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import com.training2.bookstore.product.model.Product;
@Service
public class ProductServiceJpa implements ProductService{
	@PersistenceContext EntityManager em;
	Map<String, Product> products = new HashMap<String, Product>();
// 1. pom 2. application.properties 3 coding
	public Collection<Product> listProduct() {
		TypedQuery<Product> query = em.createQuery("from Product", Product.class);
		return query.getResultList();
		
	}
	@Transactional
	public Product create(Product p) {
		String id = UUID.randomUUID().toString();
		p.setId(id);
		em.persist(p);
		return p;
	}
	@Transactional
	public Product update(Product p) {
		 return em.merge(p);
		
	}
	@Transactional
	public Product remove(String id) {
		Product entity = em.find(Product.class, id);
		em.remove(entity);
		return entity;
	}
	@Transactional
	public void storeProductImage(String productId, String storedFileId) {
		Product p = em.find(Product.class, productId);
		p.setImageLocation(storedFileId);
		em.merge(p);
		
	}
	public Collection<Product> search(String key) {
		TypedQuery<Product> query = em.createQuery("from Product where name like ?0 or desc like ?0 ", Product.class);
		query.setParameter(0, key);
		return query.getResultList();
		
	}
}
